<template>
  <div id="app" :class="{ 'dark-mode': isDarkMode, [themeClass]: true }">
    <header>
      <h1>智能 Todo 清单</h1>
      <div class="header-controls">
        <div class="theme-selector">
          <select v-model="selectedTheme" @change="changeTheme">
            <option value="default">默认主题</option>
            <option value="blue">蓝色主题</option>
            <option value="green">绿色主题</option>
            <option value="purple">紫色主题</option>
          </select>
        </div>
        <div class="theme-toggle">
          <button @click="toggleDarkMode" class="theme-btn">
            {{ isDarkMode ? '☀️' : '🌙' }}
          </button>
        </div>
      </div>
    </header>
    <main>
      <!-- 操作反馈提示 -->
      <div v-if="messageVisible" :class="['message', messageType]">
        {{ messageText }}
      </div>
      
      <AIFeatures :todos="todos" />
      <AddTodoForm @add-todo="addTodo" />
      
      <ViewSwitcher 
        :todos="todos" 
        @view-changed="handleViewChange"
        @todo-clicked="handleTodoClick"
      >
        <template #list>
          <TodoList 
            :todos="todos" 
            @toggle-complete="toggleComplete" 
            @delete-todo="deleteTodo" 
            @edit-todo="editTodo"
            @batch-complete="batchComplete"
            @batch-delete="batchDelete"
            @reorder-todos="reorderTodos"
          />
        </template>
      </ViewSwitcher>
      
      <EditTodoForm 
        :todo="currentTodo" 
        :is-visible="isEditModalVisible" 
        @update-todo="updateTodo" 
        @close="closeEditModal"
      />
    </main>
  </div>
</template>

<script>
import TodoList from './components/TodoList.vue'
import AddTodoForm from './components/AddTodoForm.vue'
import AIFeatures from './components/AIFeatures.vue'
import EditTodoForm from './components/EditTodoForm.vue'
import ViewSwitcher from './components/ViewSwitcher.vue'
import { todoAPI } from './services/api.js'

export default {
  name: 'App',
  components: {
    TodoList,
    AddTodoForm,
    AIFeatures,
    EditTodoForm,
    ViewSwitcher
  },
  data() {
    return {
      todos: [],
      isEditModalVisible: false,
      currentTodo: {},
      messageVisible: false,
      messageText: '',
      messageType: 'success',
      isDarkMode: false,
      selectedTheme: 'default',
      themeClass: 'theme-default',
      reminderInterval: null
    }
  },
  async mounted() {
    // 从本地存储中读取夜间模式设置
    const savedDarkMode = localStorage.getItem('darkMode');
    if (savedDarkMode !== null) {
      this.isDarkMode = savedDarkMode === 'true';
    }
    
    // 从本地存储中读取主题设置
    const savedTheme = localStorage.getItem('selectedTheme');
    if (savedTheme) {
      this.selectedTheme = savedTheme;
      this.updateThemeClass();
    }
    
    // 获取待办事项列表
    await this.fetchTodos();
    
    // 启动提醒检查
    this.startReminderCheck();
  },
  methods: {
    // 获取待办事项列表
    async fetchTodos() {
      try {
        const response = await todoAPI.getTodos();
        this.todos = response.data.data;
      } catch (error) {
        console.error('获取待办事项失败:', error);
        this.showNotification('获取待办事项失败！', 'error');
      }
    },
    
    // 添加待办事项
    async addTodo(newTodo) {
      try {
        const response = await todoAPI.createTodo(newTodo);
        this.todos.push(response.data.data);
        this.showNotification('任务添加成功！', 'success');
      } catch (error) {
        console.error('添加任务失败:', error);
        this.showNotification('添加任务失败！', 'error');
      }
    },
    
    changeTheme() {
      this.updateThemeClass();
      // 保存到本地存储
      localStorage.setItem('selectedTheme', this.selectedTheme);
    },
    
    updateThemeClass() {
      this.themeClass = `theme-${this.selectedTheme}`;
    },
    
    // 切换完成状态
    async toggleComplete(id) {
      try {
        const response = await todoAPI.toggleComplete(id);
        const updatedTodo = response.data.data;
        
        const index = this.todos.findIndex(t => t._id === id);
        if (index !== -1) {
          this.todos[index] = updatedTodo;
        }
        
        this.showNotification(`任务已${updatedTodo.completed ? '完成' : '取消完成'}！`, 'success');
      } catch (error) {
        console.error('切换任务状态失败:', error);
        this.showNotification('切换任务状态失败！', 'error');
      }
    },
    
    // 删除待办事项
    async deleteTodo(id) {
      if (confirm('确定要删除这个任务吗？')) {
        try {
          await todoAPI.deleteTodo(id);
          this.todos = this.todos.filter(t => t._id !== id);
          this.showNotification('任务已删除！', 'success');
        } catch (error) {
          console.error('删除任务失败:', error);
          this.showNotification('删除任务失败！', 'error');
        }
      }
    },
    
    // 编辑待办事项
    editTodo(todo) {
      this.currentTodo = { ...todo };
      this.isEditModalVisible = true;
    },
    
    // 更新待办事项
    async updateTodo(updatedTodo) {
      try {
        const response = await todoAPI.updateTodo(updatedTodo._id, updatedTodo);
        const todo = response.data.data;
        
        const index = this.todos.findIndex(t => t._id === updatedTodo._id);
        if (index !== -1) {
          this.todos[index] = todo;
        }
        
        this.showNotification('任务更新成功！', 'success');
        this.closeEditModal();
      } catch (error) {
        console.error('更新任务失败:', error);
        this.showNotification('更新任务失败！', 'error');
      }
    },
    
    closeEditModal() {
      this.isEditModalVisible = false;
      this.currentTodo = {};
    },
    
    // 批量完成
    async batchComplete(ids) {
      try {
        await todoAPI.batchTodos('complete', ids);
        // 更新本地状态
        this.todos = this.todos.map(todo => {
          if (ids.includes(todo._id)) {
            return { ...todo, completed: true, completedAt: new Date().toISOString() };
          }
          return todo;
        });
        this.showNotification(`批量完成 ${ids.length} 个任务！`, 'success');
      } catch (error) {
        console.error('批量完成任务失败:', error);
        this.showNotification('批量完成任务失败！', 'error');
      }
    },
    
    // 批量删除
    async batchDelete(ids) {
      try {
        await todoAPI.batchTodos('delete', ids);
        this.todos = this.todos.filter(t => !ids.includes(t._id));
        this.showNotification(`批量删除 ${ids.length} 个任务！`, 'success');
      } catch (error) {
        console.error('批量删除任务失败:', error);
        this.showNotification('批量删除任务失败！', 'error');
      }
    },
    
    reorderTodos(dragTodoId, event) {
      // 简单实现：在实际应用中，您可能需要更复杂的逻辑来处理重新排序
      console.log('Reordering todos:', dragTodoId, event);
      // 这里可以发送事件到父组件或直接更新 todos 数组的顺序
      this.$emit('todos-reordered');
    },
    
    handleViewChange(viewId) {
      console.log('View changed to:', viewId);
      // 在这里可以添加视图切换的逻辑
    },
    
    handleTodoClick(todo) {
      // 处理任务点击事件
      this.editTodo(todo);
    },
    
    toggleDarkMode() {
      this.isDarkMode = !this.isDarkMode;
      // 保存到本地存储
      localStorage.setItem('darkMode', this.isDarkMode);
    },
    
    startReminderCheck() {
      // 每分钟检查一次提醒
      this.reminderInterval = setInterval(() => {
        this.checkReminders();
      }, 60000);
    },
    
    checkReminders() {
      const now = new Date();
      
      this.todos.forEach(todo => {
        // 检查是否有设置提醒时间且任务未完成
        if (todo.reminderTime && !todo.completed) {
          const reminderTime = new Date(todo.reminderTime);
          
          // 检查是否到达提醒时间
          if (reminderTime <= now && reminderTime > new Date(now.getTime() - 60000)) {
            // 显示提醒通知
            this.showReminderNotification(todo);
          }
        }
      });
    },
    
    showReminderNotification(todo) {
      // 创建浏览器通知
      if (Notification.permission === 'granted') {
        new Notification(`任务提醒: ${todo.title}`, {
          body: todo.description || '您设置的任务提醒时间到了',
          icon: '/favicon.ico'
        });
      } else if (Notification.permission !== 'denied') {
        // 请求通知权限
        Notification.requestPermission().then(permission => {
          if (permission === 'granted') {
            new Notification(`任务提醒: ${todo.title}`, {
              body: todo.description || '您设置的任务提醒时间到了',
              icon: '/favicon.ico'
            });
          }
        });
      }
      
      // 显示页面内提醒
      this.showNotification(`提醒: ${todo.title}`, 'reminder');
    },
    
    showNotification(text, type = 'success') {
      this.messageText = text;
      this.messageType = type;
      this.messageVisible = true;
      
      // 3秒后自动隐藏消息
      setTimeout(() => {
        this.messageVisible = false;
      }, 3000);
    }
  }
}
</script>

<style>
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

body {
  font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
  line-height: 1.6;
  color: #333;
  background-color: #f5f5f5;
}

#app {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

header {
  text-align: center;
  margin-bottom: 30px;
  padding: 20px 0;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 5px rgba(0,0,0,0.1);
  position: relative;
}

header h1 {
  color: #2c3e50;
  font-size: 2.5rem;
}

main {
  background-color: #fff;
  padding: 25px;
  border-radius: 8px;
  box-shadow: 0 2px 5px rgba(0,0,0,0.1);
}
.message {
  padding: 15px;
  margin-bottom: 20px;
  border-radius: 4px;
  font-weight: bold;
  text-align: center;
  animation: fadeIn 0.3s;
}

.message.success {
  background-color: #d4edda;
  color: #155724;
  border: 1px solid #c3e6cb;
}

.message.error {
  background-color: #f8d7da;
  color: #721c24;
  border: 1px solid #f5c6cb;
}

@keyframes fadeIn {
  from { opacity: 0; transform: translateY(-10px); }
  to { opacity: 1; transform: translateY(0); }
}

.header-controls {
  position: absolute;
  top: 20px;
  right: 20px;
  display: flex;
  gap: 10px;
  align-items: center;
}

.theme-selector select {
  padding: 5px 10px;
  border-radius: 4px;
  border: 1px solid #ddd;
  background-color: white;
  font-size: 0.9rem;
}

.theme-toggle {
  position: relative;
  top: 0;
  right: 0;
}

.theme-btn {
  background: none;
  border: none;
  font-size: 1.5rem;
  cursor: pointer;
  padding: 5px;
  border-radius: 50%;
  transition: background-color 0.3s;
}

.theme-btn:hover {
  background-color: rgba(0,0,0,0.1);
}

.message.reminder {
  background-color: #fff3cd;
  color: #856404;
  border: 1px solid #ffeaa7;
}

/* 夜间模式样式 */
.dark-mode {
  background-color: #1a1a1a;
  color: #e0e0e0;
}

.dark-mode header {
  background-color: #2d2d2d;
  color: #e0e0e0;
}

.dark-mode main {
  background-color: #2d2d2d;
  color: #e0e0e0;
}

.dark-mode .message.success {
  background-color: #2d5a27;
  color: #d4edda;
  border-color: #2d5a27;
}

.dark-mode .message.error {
  background-color: #721c24;
  color: #f8d7da;
  border-color: #721c24;
}

.dark-mode .message.reminder {
  background-color: #5c5000;
  color: #fff3cd;
  border-color: #8c7d00;
}

/* 主题样式 */
.theme-blue {
  --primary-color: #3498db;
  --secondary-color: #2980b9;
}

.theme-green {
  --primary-color: #2ecc71;
  --secondary-color: #27ae60;
}

.theme-purple {
  --primary-color: #9b59b6;
  --secondary-color: #8e44ad;
}

.theme-blue button,
.theme-green button,
.theme-purple button {
  background-color: var(--primary-color);
}

.theme-blue button:hover,
.theme-green button:hover,
.theme-purple button:hover {
  background-color: var(--secondary-color);
}

.theme-blue .theme-btn:hover,
.theme-green .theme-btn:hover,
.theme-purple .theme-btn:hover {
  background-color: rgba(0,0,0,0.1);
}
</style>
